package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RSAAutoCertificateConfig rsaAutoCertificateConfig;

    @Autowired
    private WxPayV3Config wxPayV3Config;

    /**
     * 对接微信支付获取小程序拉起微信支付所需的参数
     *
     * @param paymentType 支付方式：订单或者充值
     * @param orderNo     订单编号
     * @return {
     * "timeStamp": "1697186259",
     * "package": "prepay_id=wx131637403639638acce1c384c2354f0000",
     * "paySign": "YoUPakYIrNI+9S4LATn+6MPW55K48vPlf2vJeJInuZsNEGaVgoVYH/SI18Gcj8N8b"
     * }
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> createJsapi(String paymentType, String orderNo) {
        try {
            //1.获取或保存本地交易记录
            PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(paymentType, orderNo);
            if (paymentInfo != null
                    && SystemConstant.ORDER_STATUS_UNPAID
                    .equals(paymentInfo.getPaymentStatus())) {
                //2.调用微信支付接口获取小程序所需的支付参数
                //2.1 构建JSAPI支付业务service
                JsapiServiceExtension service = new JsapiServiceExtension
                        .Builder()
                        .config(rsaAutoCertificateConfig)
                        .build();
                //2.2 创建预支付请求对象
                PrepayRequest request = new PrepayRequest();
                Amount amount = new Amount();
                //TODO 在开发中，将金额固定的设置为1分钱
                amount.setTotal(1);
                request.setAmount(amount);
                request.setAppid(wxPayV3Config.getAppid());
                request.setMchid(wxPayV3Config.getMerchantId());
                request.setDescription(paymentInfo.getContent());
                request.setNotifyUrl(wxPayV3Config.getNotifyUrl());
                request.setOutTradeNo(paymentInfo.getOrderNo());
                //小程序未上线之前，只允许应用下的开发者账户进行支付，因此在开发阶段需要设置付款者的信息
                Payer payer = new Payer();
                payer.setOpenid("odo3j4qp-wC3HVq9Z_D9C0cOr0Zs");
                request.setPayer(payer);

                //2.3 调用微信支付接口，获得预支付参数
                PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
                if (response != null) {
                    String timeStamp = response.getTimeStamp();
                    String nonceStr = response.getNonceStr();
                    String packageVal = response.getPackageVal();
                    String signType = response.getSignType();
                    String paySign = response.getPaySign();

                    Map<String, String> map = new HashMap<>();
                    map.put("timeStamp", timeStamp);
                    map.put("nonceStr", nonceStr);
                    map.put("package", packageVal);
                    map.put("signType", signType);
                    map.put("paySign", paySign);

                    return map;
                }

            }

            return null;
        } catch (Exception e) {
            log.error("[微信支付]创建JSAPI支付参数异常:{}", e);
            throw new RuntimeException(e);
        }
    }
}
